import {View, ScrollView} from "@tarojs/components";
import Utils from "@/utils/common";
import {Button, Cell, Empty, Search} from "@antmjs/vantui";

import {useCallback, useEffect, useRef, useState} from "react";
import {userByMobileApi, userListApi} from "@/common/apis/home_datasource";
import {UserListModel} from "@/common/apis/model";
import Taro from "@tarojs/taro";
import EventUtils from "@/utils/event_utils";

definePageConfig({
  navigationBarTitleText: '选择用户'
})

export default function UserList() {
  const [users, setUsers] = useState<UserListModel[]>()

  const eventChannel = useRef<Taro.EventChannel | null>();

  const getUserList = useCallback(() => {
    userListApi().then((res) => {
      if (res) {
        setUsers(res)
      }
    })
  }, []);

  useEffect(() => {
    getUserList()
    eventChannel.current = Utils.getChannel(Utils.getI())
  }, [getUserList]);

  const inputKey = useRef('');
  const searchAction = useCallback((e) => {
    if (!Utils.isNotBlank(e.detail) || !Utils.isPhoneNumber(e.detail)) {
      Utils.showErrorToast('请输入正确的手机号')
      return;
    }
    if (e.detail === inputKey.current) {
      return;
    }
    inputKey.current = e.detail;
    userByMobileApi(inputKey.current).then((res) => {
      if (res) {
        setUsers([res])
      }
    })

  }, []);

  return (
    <View
      style={{
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        width: '100%',
        height: '100VH',
        boxSizing: 'border-box',
        padding: '10px',
      }}
    >
      <View>
        <Search
          placeholder='请输入搜索关键词'
          onSearch={searchAction}
          renderAction={<Button type='info' onClick={() => {
            getUserList();
          }}
          >全部</Button>}
        />
      </View>
      <ScrollView scrollY style={{height: '100%'}}>
        {
          users ? users.map((user, index) => (
            <Cell key={index} title={`${user.username}(${user.mobile})`} isLink onClick={() => {
              Utils.emit(eventChannel.current, EventUtils.UserList, user)
              Utils.navigateBack()
            }}
            />)) : <Empty description='暂无数据'/>
        }
      </ScrollView>
    </View>
  )

}


